package com.mall.shopping.services;

import com.mall.shopping.IHomeService;
import com.mall.shopping.converter.ContentConverter;
import com.mall.shopping.dal.entitys.Item;
import com.mall.shopping.dal.entitys.Panel;
import com.mall.shopping.dal.entitys.PanelContent;
import com.mall.shopping.dal.entitys.PanelContentItem;
import com.mall.shopping.dal.persistence.ItemMapper;
import com.mall.shopping.dal.persistence.PanelContentMapper;
import com.mall.shopping.dal.persistence.PanelMapper;
import com.mall.shopping.dto.HomePageResponse;
import com.mall.shopping.dto.NavListResponse;
import com.mall.shopping.dto.PanelContentDto;
import com.mall.shopping.dto.PanelDto;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import java.util.HashSet;
import java.util.List;


@Service
public class IHomeServiceImpl implements IHomeService {
   @Autowired
   PanelMapper panelMapper;
   @Autowired
   PanelContentMapper panelContentMapper;
   @Autowired
   ItemMapper itemMapper;
   @Autowired
   ContentConverter contentConverter;

    /**
     * 获得主页商品信息显示
     * @return
     */
    @Override
    public HomePageResponse homepage() {
        HomePageResponse homePageResponse = new HomePageResponse();

        List<Panel> panels = panelMapper.selectAll();
        for (Panel panel : panels) {

            Integer id = panel.getId();
            Example panelContentExample = new Example(PanelContent.class);
            //找到该板块的详细信息
            panelContentExample.createCriteria().andEqualTo("panelId",id);
            List<PanelContent> panelContents = panelContentMapper.selectByExample(panelContentExample);
            List<PanelContentItem> panelContentItems = contentConverter.panenContentList2ItemList(panelContents);


            //根据详细信息找到关联的商品详情
            for (PanelContentItem i : panelContentItems) {
                Long productId = i.getProductId();
                Item item = itemMapper.selectByPrimaryKey(productId);
                if(item!=null){
                i.setProductName(item.getTitle());
                i.setSalePrice(item.getPrice());
                i.setSubTitle(item.getSellPoint());}
            }

            panel.setPanelContentItems(panelContentItems);
        }


        List<PanelDto> panelDtos = contentConverter.panelList2DtoList(panels);
        homePageResponse.setPanelContentItemDtos(new HashSet<>(panelDtos));


        return homePageResponse  ;
    }

    /**
     * 获得导航栏信息
     * @return
     */
    @Override
    public NavListResponse navigation() {
        //这里需要判空吗

        List<PanelContent> panelContents = panelContentMapper.selectAll();
        List<PanelContentDto> panelContentDtos = contentConverter.panelContents2Dto(panelContents);

        NavListResponse navListResponse = new NavListResponse();
        navListResponse.setPannelContentDtos(panelContentDtos);

        return navListResponse;
    }
}
